<?php

namespace app\task;

use app\provider\AdEventUploadProvider;
use zhanshop\App;
use zhanshop\Helper;
use zhanshop\Log;

class AdReportTask
{
    /**
     * 统计数据
     * @param string $app
     * @param string $channel
     * @param int $startTime
     * @param int $endTime
     * @return array
     */
    public static function statsAppData(string $app, string $channel, int $startTime, int $endTime)
    {
        if($channel == 'all'){
            $累计安装 = App::database()->model("visit_device")->where(['app' => $app])->whereRaw('up_aname != ""')->count();
        }else{
            $累计安装 = App::database()->model("visit_device")->where(['app' => $app, 'up_aname' => $channel])->count();
        }

        if($channel == 'all'){
            $当日安装 = App::database()->model("visit_device")->where(['app' => $app])->whereRaw('create_time >= '.$startTime.' and create_time <= '.$endTime)->whereRaw('up_aname != ""')->count();
        }else{
            $当日安装 = App::database()->model("visit_device")->where(['app' => $app, 'up_aname' => $channel])->whereRaw('create_time >= '.$startTime.' and create_time <= '.$endTime)->count();
        }

        if($channel == 'all'){
            $累计注册 = App::database()->model("visit_register")->alias('register')->join('visit_device', 'device', 'register.uuid=device.uuid')->where(['register.app' => $app])->whereRaw('device.up_aname != ""')->count();
        }else{
            $累计注册 = App::database()->model("visit_register")->alias('register')->join('visit_device', 'device', 'register.uuid=device.uuid')->where(['register.app' => $app, 'device.up_aname' => $channel])->count();
        }

        if($channel == 'all'){
            $当日新增注册 = App::database()->model("visit_register")->alias('register')->join('visit_device', 'device', 'register.uuid=device.uuid')->where(['register.app' => $app])->whereRaw('register.create_time >= '.$startTime.' and register.create_time <= '.$endTime)->whereRaw('device.up_aname != ""')->count();
        }else{
            $当日新增注册 = App::database()->model("visit_register")->alias('register')->join('visit_device', 'device', 'register.uuid=device.uuid')->where(['register.app' => $app, 'device.up_aname' => $channel])->whereRaw('register.create_time >= '.$startTime.' and register.create_time <= '.$endTime)->count();
        }

        if($channel == 'all'){
            $日活设备 = App::database()->model("visit_start")->alias('start')->join('visit_device', 'device', 'start.uuid=device.uuid')->where(['start.app' => $app, 'device.up_aname' => $channel])->whereRaw('start.create_time >= '.$startTime.' and start.create_time <= '.$endTime)->whereRaw('device.up_aname != ""')->count();
        }else{
            $日活设备 = App::database()->model("visit_start")->alias('start')->join('visit_device', 'device', 'start.uuid=device.uuid')->where(['start.app' => $app, 'device.up_aname' => $channel])->whereRaw('start.create_time >= '.$startTime.' and start.create_time <= '.$endTime)->count();
        }

        if($channel == 'all'){
            $累计支付数 = App::database()->model("visit_pay")->alias('pay')->join('visit_device', 'device', 'pay.uuid=device.uuid')->where(['pay.app' => $app])->whereRaw('device.up_aname != ""')->count();
        }else{
            $累计支付数 = App::database()->model("visit_pay")->alias('pay')->join('visit_device', 'device', 'pay.uuid=device.uuid')->where(['pay.app' => $app, 'device.up_aname' => $channel])->count();
        }

        if($channel == 'all'){
            $当日支付数 = App::database()->model("visit_pay")->alias('pay')->join('visit_device', 'device', 'pay.uuid=device.uuid')->where(['pay.app' => $app])->whereRaw('pay.create_time >= '.$startTime.' and pay.create_time <= '.$endTime)->whereRaw('device.up_aname != ""')->count();
        }else{
            $当日支付数 = App::database()->model("visit_pay")->alias('pay')->join('visit_device', 'device', 'pay.uuid=device.uuid')->where(['pay.app' => $app, 'device.up_aname' => $channel])->whereRaw('pay.create_time >= '.$startTime.' and pay.create_time <= '.$endTime)->count();
        }

        if($channel == 'all'){
            $累计支付金额 = App::database()->model("visit_pay")->alias('pay')->join('visit_device', 'device', 'pay.uuid=device.uuid')->where(['pay.app' => $app])->whereRaw('device.up_aname != ""')->sum('amount');
        }else{
            $累计支付金额 = App::database()->model("visit_pay")->alias('pay')->join('visit_device', 'device', 'pay.uuid=device.uuid')->where(['pay.app' => $app, 'device.up_aname' => $channel])->sum('amount');
        }

        if($channel == 'all'){
            $当日支付金额 = App::database()->model("visit_pay")->alias('pay')->join('visit_device', 'device', 'pay.uuid=device.uuid')->where(['pay.app' => $app])->whereRaw('pay.create_time >= '.$startTime.' and pay.create_time <= '.$endTime)->whereRaw('device.up_aname != ""')->sum('amount');
        }else{
            $当日支付金额 = App::database()->model("visit_pay")->alias('pay')->join('visit_device', 'device', 'pay.uuid=device.uuid')->where(['pay.app' => $app, 'device.up_aname' => $channel])->whereRaw('pay.create_time >= '.$startTime.' and pay.create_time <= '.$endTime)->sum('amount');
        }

        if($channel == 'all'){
            $累计支付调起 = App::database()->model("visit_order")->alias('od')->join('visit_device', 'device', 'od.uuid=device.uuid')->where(['od.app' => $app])->whereRaw('device.up_aname != ""')->count();
        }else{
            $累计支付调起 = App::database()->model("visit_order")->alias('od')->join('visit_device', 'device', 'od.uuid=device.uuid')->where(['od.app' => $app, 'device.up_aname' => $channel])->count();
        }

        if($channel == 'all'){
            $当日支付调起 = App::database()->model("visit_order")->alias('od')->join('visit_device', 'device', 'od.uuid=device.uuid')->where(['od.app' => $app])->whereRaw('od.create_time >= '.$startTime.' and od.create_time <= '.$endTime)->whereRaw('device.up_aname != ""')->count();
        }else{
            $当日支付调起 = App::database()->model("visit_order")->alias('od')->join('visit_device', 'device', 'od.uuid=device.uuid')->where(['od.app' => $app, 'device.up_aname' => $channel])->whereRaw('od.create_time >= '.$startTime.' and od.create_time <= '.$endTime)->count();
        }


        $data = [
            'app' => $app,
            'channel' => $channel,
            'dateof' => date('Y-m-d', $startTime),
            'total_install' => $累计安装,
            'install' => $当日安装,
            'total_register' => $累计注册,
            'register' => $当日新增注册,
            'active_device' => $日活设备,
            'total_payment' => $累计支付数,
            'payment' => $当日支付数,
            'total_amount' => $累计支付金额,
            'amount' => $当日支付金额,
            'total_paycall' => $累计支付调起,
            'paycall' => $当日支付调起,
            'create_time' => $startTime
        ];
        return $data;
    }
    /**
     * 每日统计
     * @return void
     */
    public function statday()
    {
        $list = App::database()->model("ad_channel")->field('app,name')->order("create_time asc")->limit(2000)->select();
        list($startTime, $endTime) = Helper::dayTimes('-1 day');
        $channel = [];
        foreach ($list as $v) {
            $channel[$v['app']] = 1;
            $insertData = $this->statsAppData($v['app'], $v['name'], $startTime, $endTime);
            try {
                App::database()->model("ad_day_report")->insert($insertData);
            }catch (\Throwable $err){
                Log::errorLog(5, substr($err->getMessage(), 0, 200));
            }
        }

        foreach ($channel as $app => $v) {
            $insertData = $this->statsAppData($app, 'all', $startTime, $endTime);
            try {
                App::database()->model("ad_day_report")->insert($insertData);
            }catch (\Throwable $err){
                Log::errorLog(5, substr($err->getMessage(), 0, 200));
            }
        }
    }

    /**
     * 今日统计
     * @return void
     */
    public function statnow()
    {
        $list = App::database()->model("ad_channel")->field('app,name')->limit(2000)->select();
        list($startTime, $endTime) = Helper::dayTimes();
        $channel = [];
        foreach ($list as $v) {
            $channel[$v['app']] = 1;
            $insertData = $this->statsAppData($v['app'], $v['name'], $startTime, $endTime);
            $id = App::database()->model("ad_now_report")->where(['app' => $v['app'], 'channel' => $v['name']])->value("id");
            if($id){
                $insertData['update_time'] = time();
                App::database()->model("ad_now_report")->where(['id' => $id])->update($insertData);
            }else{
                App::database()->model("ad_now_report")->insert($insertData);
            }
        }

        foreach ($channel as $app => $v) {
            $insertData = $this->statsAppData($app, 'all', $startTime, $endTime);
            $id = App::database()->model("ad_now_report")->where(['app' => $app, 'channel' => 'all'])->value("id");
            if($id){
                $insertData['update_time'] = time();
                App::database()->model("ad_now_report")->where(['id' => $id])->update($insertData);
            }else{
                App::database()->model("ad_now_report")->insert($insertData);
            }
        }
    }

    /**
     * 清理7天前以前的广告监测数据
     * @return void
     */
    public function cleanListen()
    {
        $logExpireDays = App::env()->get('LOG_EXPIRE_DAYS', "7");
        $lastDate = intval(date('Ymd', strtotime('-'.$logExpireDays.' day')));
        $files = glob(App::runtimePath().'/log/*.log');
        foreach ($files as $file){
            $paths = explode('/', explode('.log', $file)[0]);
            $fileName = intval($paths[count($paths) - 1]);
            if($fileName < $lastDate){
                @unlink($file);
            }
        }

        $cleanTime = strtotime("-".$logExpireDays." day");
        App::database()->model("ad_record")->whereRaw("create_time < ".$cleanTime)->delete();
    }

    /**
     * 广告上报修补
     * @return void
     */
    public function uploadMend()
    {
        $devices = App::database()->model("visit_device")->whereRaw("create_time >= ".(time() - 3600 * 24).' and create_time <= '.(time() - 1800))->where(["up_aid" => 0])->limit(2000)->order('create_time desc')->select();
        foreach ($devices as $k => $v){
            // 上报激活
            list($aduid, $platform) = App::make(AdEventUploadProvider::class)->upload($v['app'], 'all', 'activate', [
                'oaid' => $v['oaid'],
                'imei' => $v['imei'],
                'android_id' => $v['android_id'],
                'idfa' => $v['idfa'],
                'iddi' => $v['iddi'],
                'mac' => $v['mac'],
                'ua' => $v['ua'],
                'brand' => $v['brand'],
                'unit_type' => $v['unit_type'],
                'ipv4' => $v['ipv4'],
                'ipv6' => $v['ipv6'],
            ]);
            if($aduid){
                App::database()->model("visit_device")->where(['uuid' => $v['uuid']])->update(['up_aid' => $aduid, 'up_aname' => $platform]); // 更新广告来源
                App::database()->model("ad_upload")->where(['id' => $aduid])->update(['uuid' => $v['uuid']]); // 更新广告绑定

                // 查询是否有注册
                $registers = App::database()->model("visit_register")->where(['uuid' => $v['uuid'], "up_aid" => "0"])->limit(1)->select(); // 查询已注册但没有上报的记录
                foreach ($registers as $register) {
                    list($aduid, $platform) = App::make(AdEventUploadProvider::class)->upload($v['app'], 'all', 'register', [
                        'uuid' => $v['uuid']
                    ], [
                        'user_id' => $register["user_id"],
                    ]);
                    if($aduid){
                        App::database()->model("visit_register")->where(["id" => $register["id"]])->update(['up_aid' => $aduid]);
                    }
                }

                // 查询是否有下单
                $orders = App::database()->model("visit_order")->where(['uuid' => $v['uuid'], "up_aid" => "0"])->limit(5)->select();
                foreach ($orders as $order) {
                    list($aduid, $platform) = App::make(AdEventUploadProvider::class)->upload($v['app'], 'all', 'order', [
                        'uuid' => $v["uuid"]
                    ], [
                        'order_id' => $order["order_id"],
                        'user_id' => $order["user_id"],
                        'pay_way' => $order["pay_way"],
                        'amount' => $order["amount"],
                    ]);
                    if($aduid){
                        App::database()->model("visit_order")->where(["id" => $order["id"]])->update(['up_aid' => $aduid]);
                    }
                }

                // 查询是否有付费
                $orders = App::database()->model("visit_pay")->where(['uuid' => $v['uuid'], "up_aid" => "0"])->limit(5)->select();
                foreach ($orders as $order) {
                    list($aduid, $platform) = App::make(AdEventUploadProvider::class)->upload($v['app'], 'all', 'pay', [
                        'uuid' => $v["uuid"]
                    ], [
                        'order_id' => $order["order_id"],
                        'user_id' => $order["user_id"],
                        'pay_way' => $order["pay_way"],
                        'amount' => $order["amount"],
                    ]);
                    if($aduid){
                        App::database()->model("visit_pay")->where(["id" => $order["id"]])->update(['up_aid' => $aduid]);
                    }
                }
            }
        }
    }
}